import React, { useState, useEffect } from 'react';
import { Card, Input, Button, Row, Col, message } from 'antd';
import styled from 'styled-components';
import { Joystick } from 'react-joystick-component';
import { throttle } from '../utils/throttle';
import { API_BASE_URL } from '../config';

const Container = styled.div`
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
`;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-size: 16px;
    padding: 12px 0;
  }
`;

const EmojiButton = styled(Button)`
  font-size: 24px;
  height: 60px;
  width: 60px;
  margin: 4px;
`;

const QuickMessageButton = styled(Button)`
  margin: 4px;
  font-size: 14px;
  height: 32px;
  padding: 0 15px;
`;

const ArmControlButton = styled(Button)`
  margin: 4px;
  min-width: 120px;
  height: 32px;
  font-size: 14px;
`;

const AdminPanel: React.FC = () => {
  const [messageText, setMessageText] = useState('');
  
  // 添加 updateState 函数
  const updateState = async (data: { emoji?: string; message?: string }) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/update`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      });
      
      if (response.ok) {
        message.success('更新成功');
      } else {
        throw new Error('更新失败');
      }
    } catch (error) {
      console.error('更新状态失败:', error);
      message.error('更新失败，请检查后端服务是否正常运行');
    }
  };

  // 预设的表情和消息
  const emojiList = [
    { emoji: '🤖', label: '机器人' },
    { emoji: '😀', label: '开心' },
    { emoji: '😃', label: '大笑' },
    { emoji: '😄', label: '笑眼' },
    { emoji: '😁', label: '露齿笑' },
    { emoji: '😆', label: '眯眼笑' },
    { emoji: '😅', label: '尴尬笑' },
    { emoji: '🤣', label: '笑倒' },
    { emoji: '😂', label: '笑哭' },
    { emoji: '🥲', label: '感动' },
    { emoji: '😊', label: '害羞' },
    { emoji: '😇', label: '天使' },
    { emoji: '😉', label: '眨眼' },
    { emoji: '😍', label: '爱心眼' },
    { emoji: '🥰', label: '幸福' },
    { emoji: '😘', label: '飞吻' },
    { emoji: '😗', label: '亲亲' },
    { emoji: '😛', label: '调皮' },
    { emoji: '😜', label: '俏皮' },
    { emoji: '🤪', label: '搞怪' },
    { emoji: '😎', label: '酷' },
    { emoji: '🧐', label: '思考' },
    { emoji: '🤓', label: '书呆子' },
    { emoji: '😤', label: '得意' }
  ];

  const quickMessages = [
    { text: '你好呀，我是家政小祥，一款基于大语言模型的模块化多功能管家型机器人，请问有什么我能够帮助您的吗？', audioIndex: 1 },
    { text: '您看起来心情不是很好，我来给您跳支舞吧！', audioIndex: 2 },
    { text: '您的狗狗好像有点饿，我来给它喂点食物吧！', audioIndex: 3 },
    { text: '您的植物需要浇水了，我来帮您浇水吧！', audioIndex: 4 },
    { text: '家里好像有点脏乱哦，我来收拾下吧！', audioIndex: 5 },
    { text: '这一块玻璃脏脏的，我来帮您擦干净吧！', audioIndex: 6 },
    { text: '今天天气阴转多云，晚上可能有小雨，出行记得带伞哦！', audioIndex: 7 }
  ];

  const armPoses = [
    '监视位姿',
    '休息位姿',
    '工作位姿',
    '准备位姿'
  ];

  const monitorMessages = [
    '检测到陌生人！',
    '警告：发现异常行为',
    '门窗状态正常',
    '空气质量良好',
    '检测到宠物活动',
    '房间光照充足'
  ];

  const handleMonitorMessage = async (msg: string) => {
    try {
      await fetch(`${API_BASE_URL}/api/monitor/send`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ message: msg }),
      });
      message.success('发送成功');
    } catch (error) {
      message.error('发送失败');
    }
  };

  // 使用节流函数包装请求
  const throttledJoystickMove = React.useCallback(
    throttle(async (data: any) => {
      try {
        const x = Math.round(data.x * 100) / 100;
        const y = Math.round(data.y * 100) / 100;
        await fetch(`${API_BASE_URL}/api/move?x=${x}&y=${y}`);
      } catch (error) {
        console.error('移动控制失败:', error);
      }
    }, 100), // 限制为每100ms最多发送一次请求
    []
  );

  const handleJoystickMove = (data: any) => {
    if (data.x === 0 && data.y === 0) {
      // 停止移动时立即发送停止请求
      fetch(`${API_BASE_URL}/api/move?x=0&y=0`).catch(console.error);
    } else {
      throttledJoystickMove(data);
    }
  };

  const handleArmControl = async (pose: string) => {
    try {
      await fetch(`${API_BASE_URL}/api/arm?pose=${pose}`);
      message.success(`已切换到${pose}`);
    } catch (error) {
      message.error('控制失败');
    }
  };

  const handleSpeak = async (text: string) => {
    try {
      await fetch(`${API_BASE_URL}/api/speak`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ message: text }),
      });
    } catch (error) {
      console.error('语音播放失败:', error);
    }
  };

  return (
    <Container>
      <Row gutter={[16, 16]}>
        <Col span={24} lg={12}>
          <StyledCard title="表情控制">
            <div style={{ display: 'flex', flexWrap: 'wrap' }}>
              {emojiList.map(({ emoji, label }) => (
                <EmojiButton
                  key={emoji}
                  onClick={() => updateState({ emoji })}
                  title={label}
                >
                  {emoji}
                </EmojiButton>
              ))}
            </div>
          </StyledCard>

          <StyledCard title="对话内容控制">
            <Input.TextArea
              rows={4}
              value={messageText}
              onChange={(e) => setMessageText(e.target.value)}
              style={{ 
                marginBottom: 16,
                fontSize: '14px',
                padding: '8px',
                minHeight: '100px'
              }}
            />
            <div style={{ display: 'flex', flexWrap: 'wrap', marginBottom: 16 }}>
              {quickMessages.map(({ text, audioIndex }) => (
                <QuickMessageButton
                  key={text}
                  onClick={() => {
                    setMessageText(text);
                    updateState({ message: text });
                  }}
                >
                  {text}
                </QuickMessageButton>
              ))}
              <Button 
                type="primary"
                onClick={() => updateState({ message: messageText })}
              >
                更新对话内容
              </Button>
            </div>
          </StyledCard>
        </Col>

        <Col span={24} lg={12}>
          <StyledCard title="移动控制">
            <div style={{ display: 'flex', justifyContent: 'center', padding: '20px' }}>
              <Joystick
                size={150}
                baseColor="#002FA7"
                stickColor="#FF5252"
                move={handleJoystickMove}
                stop={() => fetch(`${API_BASE_URL}/api/move?x=0&y=0`)}
              />
            </div>
          </StyledCard>

          <StyledCard title="机械臂控制">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
              {armPoses.map(pose => (
                <ArmControlButton
                  key={pose}
                  onClick={() => handleArmControl(pose)}
                >
                  {pose}
                </ArmControlButton>
              ))}
            </div>
          </StyledCard>

          <StyledCard title="监控消息发送">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
              {monitorMessages.map(msg => (
                <QuickMessageButton
                  key={msg}
                  onClick={() => handleMonitorMessage(msg)}
                >
                  {msg}
                </QuickMessageButton>
              ))}
            </div>
          </StyledCard>
        </Col>
      </Row>
    </Container>
  );
};

export default AdminPanel;
